﻿package com.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.entity.User;
import com.web.filter.AbstractFilter;

public class LoginValidateFilter extends AbstractFilter{

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		
		String uri = request.getRequestURI(); 
		uri = uri.substring(uri.lastIndexOf("/") + 1);
		
		
		if("".equals(uri) || "index.jsp".equals(uri) || "login.jspx".equals(uri)) {
			chain.doFilter(request, response);
		} else {
			HttpSession session = request.getSession();
			
			User user = (User) session.getAttribute("user");
			
			if(user == null) {
				String url = request.getRequestURL().toString();
				String queryString = request.getQueryString();
				
				if(queryString != null) {
					url = url + "?" + queryString;
				}
				
				session.setAttribute("where", url);
				
				response.sendRedirect("login.jspx?code=10002");
			} else {
				chain.doFilter(request, response);
			}
		}
		
	}

}
